<?php
header("Content-type:text/html;Charset=utf-8");

//备忘录
class Memento{
    public $id;
    public $name;
    public $liveLevel;
    
    function __construct($id,$name,$liveLevel){
        $this->id = $id;
        $this->name = $name;
        $this->liveLevel = $liveLevel;
    }
}

//备忘录管理器
class Originator{
    public static $mementos = array();
    private static $instance = null;
    
    //单例模式确保只有一个管理器
    private function __construct(){
        
    }
    //返回单例对象
    static function getInstance(){
        if(!(self::$instance instanceOf slef)){
            self::$instance = new self();
        }
        return self::$instance;
    }
    //存备忘录
    function setMemento($id,Memento $memento){
        self::$mementos[$id] = $memento;
    }
    //取备忘录
    function getMemento($id){
        return self::$mementos[$id];
    }
}

//创建者，玩家，可存取自身状态
class Player{
    private static $i = 0;  //静态变量累加用于给$id赋值
    public $id; //每个对象独一无二，用于保存状态备忘录到管理器
    private $name; //姓名
    private $liveLevel;  //生命值
    
    function __construct($name){
        $this->name = $name;
        $this->id = self::$i;
        self::$i++;
    }
    //初始化
    function init(){
        $this->liveLevel = 100;
    }
    
    //生命值减少10
    function damage(){
        $this->liveLevel -=10;
    }
    
    //显示现有状态
    function displayState(){
        echo "姓  名：".$this->name."<br/>";
        echo "生命值：".$this->liveLevel."<br/>";
    }
    
    //保存状态到一个备忘录中，该备忘录将被放置到管理器中
    function saveState(){
        $originator = Originator::getInstance();
        $originator->setMemento($this->id,new Memento($this->id,$this->name,$this->liveLevel));
    }
    //恢复备忘录
    function getState(){
        $originator = Originator::getInstance();
        $memento = $originator->getMemento($this->id);
        $this->id = $memento->id;
        $this->name = $memento->name;
        $this->liveLevel = $memento->liveLevel;
    }
}

//测试
//创建、初始化角色并显示状态
$player = new Player("张三");
$player->init();
$player->displayState(); //生命值100

//开始游戏前存档
$player->saveState();

//开始游戏,收到伤害生命值减少，显示状态
$player->damage();
$player->damage();
$player->displayState(); //生命值80

//回档恢复原来状态，显示状态
$player->getState();
$player->displayState();  //生命值100

